<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旅行家 - 注册/登录</title>
    <link href="css/reg.css" rel="stylesheet" type="text/css"/>
    <style>

    </style>

</head>
<body>
<div class="container" id="app">
    <h1>旅行家</h1>

    <div class="tab-container">
        <div class="tab" :class="{active: activeTab === 'register'}" @click="switchTab('register')">注册</div>
        <div class="tab" :class="{active: activeTab === 'login'}" @click="switchTab('login')">登录</div>
    </div>

<!--    <div class="tab-container">-->
<!--        <div class="tab active" data-tab="register">注册</div>-->
<!--        <div class="tab" data-tab="login">登录</div>-->
<!--    </div>-->

    <!-- 注册表单 -->
    <div class="form-section" :class="{active: activeTab === 'register'}">
<!--    <div class="form-section active" id="register-form">-->
        <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
        <div v-if="successMessage" class="success-message">{{ successMessage }}</div>

        <div class="form-group">
            <label class="form-section active">选择头像</label>
            <div class="avatar-container">
                <img @click="selectHead('img/boy1.png')" src="img/boy1.png"
                     :class="['head-option', {selected: head === 'img/boy1.png'}]">
                <img @click="selectHead('img/boy2.png')" src="img/boy2.png"
                     :class="['head-option', {selected: head === 'img/boy2.png'}]">
                <img @click="selectHead('img/girl1.png')" src="img/girl1.png"
                     :class="['head-option', {selected: head === 'img/girl1.png'}]">
                <img @click="selectHead('img/girl2.png')" src="img/girl2.png"
                     :class="['head-option', {selected: head === 'img/girl2.png'}]">
            </div>
            <input type="hidden" id="head" :value="head">
        </div>

        <div class="form-group">
            <label for="uname">用户名</label>
            <input v-model="registerForm.uname" id="uname" placeholder="请输入您的用户名">
        </div>

        <div class="form-group">
            <label for="zhanghao">账号</label>
            <input v-model="registerForm.zhanghao" id="zhanghao" placeholder="请输入账号(不能包含空格、斜杠或下划线)">
        </div>

        <div class="form-group">
            <label for="password">密码</label>
            <input v-model="registerForm.password" id="password" type="password" placeholder="请输入密码">
            <div class="password-strength">
                <div class="password-strength-bar" id="password-strength-bar"></div>
            </div>
        </div>

        <div class="form-group">
            <label for="email">邮箱</label>
            <input v-model="registerForm.email" id="email" placeholder="请输入您的邮箱">
        </div>

        <div class="form-group">
            <label>邮箱验证码</label>
            <div class="verification-code">
                <input type="text" v-model="registerForm.verificationCode" placeholder="请输入验证码">
                <!-- 发送验证码按钮 -->
                <button @click="sendVerificationCode" :disabled="isSendingCode || !registerForm.email">
                    {{ isSendingCode ? `${countdown}秒后重新发送` : '发送验证码' }}
                </button>
            </div>
        </div>

        <!-- 注册按钮 -->
        <button class="submit-btn" @click="register">注册</button>
    </div>

    <!-- 登录表单 -->
    <div class="form-section" :class="{active: activeTab === 'login'}">
        <!-- 登录成功后的用户信息展示 -->
        <div v-if="loginSuccess" class="login-success-container">
            <div class="avatar-preview">
                <img :src="loggedInUser.head" alt="用户头像">
            </div>
            <h3>欢迎回来, {{ loggedInUser.uname }}!</h3>
            <p>正在跳转到首页...</p>
        </div>
        <!--    <div class="form-section active" id="register-form">-->
<!--    <div class="form-section" id="login-form">-->
        <div class="form-group">
            <label>账号</label>
            <input type="text" v-model="loginForm.zhanghao" placeholder="请输入您的账号">
            <div class="error-message" id="login-zhanghao-error"></div>
        </div>

        <div class="form-group">
            <label>密码</label>
            <input v-model="loginForm.password" type="password" placeholder="请输入密码">
            <div class="error-message" id="login-password-error"></div>
        </div>

        <!-- 验证码 -->
        <div class="form-group">
            <label>验证码:</label>
            <div class="captcha-container">
                <input v-model="loginForm.captcha" type="text" class="form-control" placeholder="请输入验证码" style="width: 100px;">
                <img :src="captchaUrl" @click="refreshCaptcha" class="captcha-img"
                 :title="'点击刷新验证码'">
                <div class="error-message" id="login-captcha-error"></div>
            </div>
        </div>

        <button class="submit-btn" @click="login">登录</button>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            loginSuccess: false, // 新增：登录成功状态
            loginedInUser: {
              uname:'',
              head:''
            },
            // 表单数据
            activeTab: 'register',
            head: '1',
            registerForm: {
                uname: '',
                zhanghao: '',
                password: '',
                email: '',
                verificationCode: ''
            },
            loginForm: {
                zhanghao: '',
                password: '',
                captcha: ''
            },
            errorMessage: null,
            successMessage: null,
            isSendingCode: false,
            countdown: 0,
            captchaUrl: '/lvuser/captcha?' + Math.random(),
            // 其他数据...
        },
        methods: {
            // 切换标签
            switchTab(tab) {
                this.activeTab = tab;
            },

            // 选择头像
            selectHead(head) {
                this.head = head;
                // 更新头像选中状态
                document.querySelectorAll('.head-option').forEach(el => {
                    el.classList.remove('selected');
                });
                event.target.classList.add('selected');
            },

            // 发送验证码
            async sendVerificationCode() {
                try {
                    // 发送验证码时添加防重复点击
                    axios.defaults.withCredentials = true;
                    const response = await axios.post('/lvuser/send-code', {
                        email: this.registerForm.email
                    },{
                        withCredentials: true
                    });
                    // 成功发送后禁用按钮60秒
                    // setTimeout(() => {
                    // }, 60000);
                    if (response.data.code === 1) {
                        alert('验证码已发送');
                    } else {
                        alert(response.data.message);
                    }
                } catch (error) {
                    alert('发送验证码失败');
                }
            },

            // 注册
            async register() {
                // 实现注册逻辑
                try {
                    const registerData = {
                        head: this.head,
                        uname: this.registerForm.uname,
                        zhanghao: this.registerForm.zhanghao,
                        password: this.registerForm.password,
                        email: this.registerForm.email,
                        // 确保从输入框获取值时去除空格
                        verificationCode: this.registerForm.verificationCode.trim()
                    };

                    console.log("发送的注册数据:", registerData); // 调试

                    //调用注册API
                    const response = await axios.post('/lvuser/register', registerData,{
                        withCredentials: true
                    });

                    //处理响应
                    if (response.data.code === 1) {
                        this.successMessage = response.data.message;
                        //注册成功后清空表单
                        this.registerForm = {
                            uname: '',
                            zhanghao: '',
                            password: '',
                            email: '',
                            verificationCode: ''
                        };
                        //3秒后自动跳转到登录
                        setTimeout(() => {
                            this.activeTab = "login";
                        }, 3000);
                    } else {
                        this.errorMessage = response.data.message;
                    }
                }catch(error){
                    console.error("注册错误详情:", error.response); // 打印完整错误信息
                    this.errorMessage = error.response?.data?.message || '注册失败，请稍后重试';
                }
            },

            // 登录
            login() {
                // 实现登录逻辑
                let q = new URLSearchParams();
                q.append("zhanghao",this.loginForm.zhanghao);
                q.append("password",this.loginForm.password);
                q.append("captcha",this.loginForm.captcha);
                axios.post('/lvuser/login',q,{
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).then(response => {
                    console.log('完整响应：',response.data);
                    if (response.data.code === 1) {
                        // 确保正确获取嵌套的data对象
                        const userData = response.data.data || {};
                        //存储用户信息
                        const userInfo = {
                            uid: userData.uid || '',
                            uname: userData.uname || '',
                            head: userData.head || 'img/boy1.png',
                            zhanghao: this.loginForm.zhanghao,
                            gender: userData.gender || 0,
                            email: userData.email || '',
                            status: userData.status || 0,
                            level: userData.level || 0,
                            createAt: userData.createAt || '',  // 注意字段名改为驼峰
                            updateAt: userData.updateAt || '',  // 注意字段名改为驼峰
                            birthday: userData.birthday || '',
                            bio: userData.bio || '这个人很懒，什么都没留下...'
                        };

                        // 存储到Vue实例和localStorage

                        localStorage.setItem('userInfo', JSON.stringify(userInfo));

                        console.log(JSON.parse(localStorage.getItem('userInfo')));

                        //显示登录成功状态
                        this.loginSuccess = true;
                        this.loggedInUser = userInfo;

                        // 跳转到首页 - 使用相对路径
                        setTimeout(() => {
                            if (localStorage.getItem('userInfo')){
                                location.href = "/lv-index/index1.html"; // 或 location.href = "index.html";
                            }else {
                                alert("登录失败，请重试");
                                this.refreshCaptcha();
                            }
                        }, 3000);
                    } else {
                        alert(response.data.msg || "登录失败");
                        this.refreshCaptcha(); //刷新验证码
                        this.loginForm.captcha = ''; //清空验证码
                    }
                }).catch(error => {
                    alert("请求失败: " + error.message);
                    this.refreshCaptcha();
                });
            },
            //刷新验证码
            refreshCaptcha() {
                this.captchaUrl = '/lvuser/captcha?' + Math.random();
            },
        }
    });
</script>
</body>
</html>